package com.zzcy.bt_print_plugin.base;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.zzcy.bt_print_plugin.R;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: dhd
 * @date: 2024/1/3
 * Describe : 写点什么解释一下这个类
 */
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
    private List<BluetoothDevice> mData;

    public MyAdapter() {
        mData = new ArrayList<>();
    }

    public List<BluetoothDevice> getDataList() {
        return mData;
    }

    public void addData(BluetoothDevice bluetoothDevice) {
        mData.add(bluetoothDevice);
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_device, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        BluetoothDevice bluetoothDevice = mData.get(position);
        holder.bind(bluetoothDevice);
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        private TextView tvName;
        private TextView tvAddress;
        private Button btnConnect;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvName = itemView.findViewById(R.id.tvName);
            tvAddress = itemView.findViewById(R.id.tvAddress);
            btnConnect = itemView.findViewById(R.id.btnConnect);
        }

        @SuppressLint("MissingPermission")
        public void bind(BluetoothDevice bluetoothDevice) {
            String name = bluetoothDevice.getName();
            if (name == null || TextUtils.isEmpty(name)) {
                tvName.setText("N/A");
            } else {
                tvName.setText(name);
            }
            tvAddress.setText(bluetoothDevice.getAddress());
            btnConnect.setOnClickListener(v -> {
                if (onClickItem != null) {
                    onClickItem.onClickItem(tvAddress.getText().toString().trim());
                }
            });
        }
    }

    public void clearAdaper() {
        mData.clear();
        notifyDataSetChanged();
    }

    public interface OnClickItem {

        void onClickItem(String address);

    }

    OnClickItem onClickItem;

    public void setOnClickItem(OnClickItem onClickItem) {
        this.onClickItem = onClickItem;
    }

}
